package com.ticket.sass.common.ticketserver.utils

import mu.KotlinLogging
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okio.Buffer
import java.nio.charset.Charset
import java.time.Duration
import java.time.LocalDateTime


/**
 * @author 朱其鹏
 * @date 2023/11/17 11:34
 */
object HttpClient {
    private val logger = KotlinLogging.logger {}

    private val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(Interceptor { chain ->
            val request = chain.request()

            val requestBody = request.body?.let {
                val requestBodyBuffer = Buffer()
                it.writeTo(requestBodyBuffer)
                requestBodyBuffer.readString(Charset.forName("UTF-8"))
            }

            val beginTime = LocalDateTime.now()
            val response = chain.proceed(request)

            val responseBody = response.body?.let {
                it.source().request(Long.MAX_VALUE)
                it.source().buffer.clone().readString(Charset.forName("UTF-8"))
            }

            val endTime = LocalDateTime.now()
            val between = Duration.between(beginTime, endTime)
            val millis = between.toMillis()

            logger.info("请求时间：${millis}毫秒, 请求地址：${request.url}，请求参数：${requestBody}，响应状态码：${response.code}，响应数据：${responseBody}")

            response
        })
        .build()

    /**
     * POST 请求
     *
     * @param params    请求数据
     *
     * @return 响应数据
     *
     */
    fun post(url: String, params: Map<String, *>): String? {
        val queryString = params.map { (key, value) -> "$key=$value" }.joinToString("&")

        val mediaType = "application/x-www-form-urlencoded".toMediaType()

        val request = Request.Builder()
            .url(url)
            .method("POST", queryString.toRequestBody(mediaType))
            .addHeader("Content-Type", "application/x-www-form-urlencoded")
            .build()

        return okHttpClient.newCall(request).execute().body?.string()
    }
}
